<template>
  <div class="login">
    <el-form :model="dataForm" :rules="rules" ref="Form" class="form">
      <el-form-item prop="username" class="form-item">
        <el-input
          v-model="dataForm.username"
          placeholder="用户名/手机"
          @focus="chearRules('username')"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password" class="form-item">
        <el-input
          v-model="dataForm.password"
          placeholder="密码"
          type="password"
          @focus="chearRules('password')"
        ></el-input>
      </el-form-item>
      <p class="form-text">
        <nuxt-link to="#">忘记密码</nuxt-link>
      </p>
      <el-button class="submit" type="primary" @click="handleLoginSubmit">
        登录
      </el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 登录表单数据
      dataForm: {
        username: "13800138000", // 用户名
        password: "123456", // 密码
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    //   输入框聚焦时清除规则
    chearRules(propName) {
      this.$refs.Form.clearValidate(propName);
    },

    handleLoginSubmit() {
      // 发送请求前的一次保底总校验  this.$refs.form.validate()
      //  valid 为true表示没有错误
      this.$refs.Form.validate(async (valid) => {
        if (valid) {
          // 用在 vuex  action里面封装异步操作进行登录操作
          this.$store.dispatch("userstore/login", this.dataForm);
          this.$message.success("登录成功");
          this.$router.push('/')
          // this.$router.push("/");
        } else {
          this.$message.warning("请输入合法用户名及密码");
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>